'use client';

import { useState } from 'react';
import { 
  Search, 
  Plus, 
  Award,
  Users,
  Clock,
  ThumbsUp,
  ThumbsDown,
  AlertCircle,
  Edit,
  Trash2
} from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { FadeIn } from '@/components/ui/motion';

// 模拟数据
const mockStudents = [
  { id: 1, name: '张三', studentId: '20230001' },
  { id: 2, name: '李四', studentId: '20230002' },
  { id: 3, name: '王五', studentId: '20230003' },
  { id: 4, name: '赵六', studentId: '20230004' },
  { id: 5, name: '钱七', studentId: '20230005' },
];

const mockRewards = [
  {
    id: 1,
    studentId: '20230001',
    studentName: '张三',
    type: '奖励',
    reason: '数学竞赛一等奖',
    description: '在市级数学竞赛中获得一等奖，表现优异。',
    status: 'pending',
    date: '2023-10-15'
  },
  {
    id: 2,
    studentId: '20230002',
    studentName: '李四',
    type: '奖励',
    reason: '优秀班干部',
    description: '担任班长期间，工作认真负责，深受同学信任。',
    status: 'approved',
    date: '2023-10-14'
  },
  {
    id: 3,
    studentId: '20230003',
    studentName: '王五',
    type: '惩罚',
    reason: '课堂扰乱秩序',
    description: '上课期间多次讲话，影响课堂秩序。',
    status: 'rejected',
    date: '2023-10-13'
  }
];

const rewardTypes = ['奖励', '惩罚'];
const reasonOptions = {
  '奖励': ['学科竞赛获奖', '优秀班干部', '文明学生', '进步显著', '助人为乐'],
  '惩罚': ['课堂扰乱秩序', '作业缺交', '考试作弊', '打架斗殴', '违反校规']
};

export default function RewardSubmitPage() {
  const [searchTerm, setSearchTerm] = useState('');
  const [dialogOpen, setDialogOpen] = useState(false);
  const [rewards, setRewards] = useState(mockRewards);
  
  // 新奖惩记录表单状态
  const [newReward, setNewReward] = useState({
    studentId: '',
    type: '',
    reason: '',
    description: ''
  });
  
  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setNewReward(prev => ({ ...prev, [name]: value }));
  };
  
  // 处理类型选择变化
  const handleTypeChange = (value: string) => {
    setNewReward(prev => ({ ...prev, type: value, reason: '' }));
  };
  
  // 处理原因选择变化
  const handleReasonChange = (value: string) => {
    setNewReward(prev => ({ ...prev, reason: value }));
  };
  
  // 处理学生选择变化
  const handleStudentChange = (value: string) => {
    setNewReward(prev => ({ ...prev, studentId: value }));
  };
  
  // 提交奖惩记录
  const handleSubmitReward = () => {
    const student = mockStudents.find(s => s.studentId === newReward.studentId);
    if (!student) return;
    
    const newRewardItem = {
      id: rewards.length + 1,
      studentId: student.studentId,
      studentName: student.name,
      type: newReward.type,
      reason: newReward.reason,
      description: newReward.description,
      status: 'pending',
      date: new Date().toISOString().split('T')[0]
    };
    
    setRewards([newRewardItem, ...rewards]);
    setDialogOpen(false);
    setNewReward({
      studentId: '',
      type: '',
      reason: '',
      description: ''
    });
    
    // 实际项目中应该调用API保存数据
    console.log('提交奖惩记录', newRewardItem);
  };
  
  // 删除奖惩记录
  const handleDeleteReward = (id: number) => {
    if (window.confirm('确定要删除这条记录吗？')) {
      setRewards(rewards.filter(r => r.id !== id));
      // 实际项目中应该调用API删除数据
      console.log('删除奖惩记录', id);
    }
  };
  
  // 过滤奖惩记录列表
  const filteredRewards = rewards.filter(reward => 
    reward.studentName.toLowerCase().includes(searchTerm.toLowerCase()) || 
    reward.studentId.includes(searchTerm) ||
    reward.reason.toLowerCase().includes(searchTerm.toLowerCase())
  );

  // 统计数据
  const pendingCount = rewards.filter(r => r.status === 'pending').length;
  const approvedCount = rewards.filter(r => r.status === 'approved').length;
  const rejectedCount = rewards.filter(r => r.status === 'rejected').length;

  return (
    <FadeIn>
      <div className="container mx-auto py-6">
        <div className="flex justify-between items-center mb-6">
          <h1 className="text-2xl font-bold">奖惩提交</h1>
          <div className="flex space-x-2">
            <div className="relative">
              <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-500" />
              <Input
                type="search"
                placeholder="搜索学生或记录..."
                className="pl-8 w-[200px] md:w-[250px]"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
              <DialogTrigger asChild>
                <Button className="flex items-center">
                  <Plus className="mr-2 h-4 w-4" />
                  提交记录
                </Button>
              </DialogTrigger>
              <DialogContent className="sm:max-w-[500px]">
                <DialogHeader>
                  <DialogTitle>提交奖惩记录</DialogTitle>
                  <DialogDescription>
                    为学生提交奖惩记录，等待管理员审批
                  </DialogDescription>
                </DialogHeader>
                <div className="grid gap-4 py-4">
                  <div className="grid gap-2">
                    <Label htmlFor="student">选择学生</Label>
                    <Select value={newReward.studentId} onValueChange={handleStudentChange}>
                      <SelectTrigger>
                        <SelectValue placeholder="选择学生" />
                      </SelectTrigger>
                      <SelectContent>
                        {mockStudents.map(student => (
                          <SelectItem key={student.id} value={student.studentId}>
                            {student.name} ({student.studentId})
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="grid gap-2">
                    <Label htmlFor="type">记录类型</Label>
                    <Select value={newReward.type} onValueChange={handleTypeChange}>
                      <SelectTrigger>
                        <SelectValue placeholder="选择类型" />
                      </SelectTrigger>
                      <SelectContent>
                        {rewardTypes.map(type => (
                          <SelectItem key={type} value={type}>
                            {type}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  {newReward.type && (
                    <div className="grid gap-2">
                      <Label htmlFor="reason">具体原因</Label>
                      <Select value={newReward.reason} onValueChange={handleReasonChange}>
                        <SelectTrigger>
                          <SelectValue placeholder="选择原因" />
                        </SelectTrigger>
                        <SelectContent>
                          {reasonOptions[newReward.type as keyof typeof reasonOptions].map(reason => (
                            <SelectItem key={reason} value={reason}>
                              {reason}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  )}
                  <div className="grid gap-2">
                    <Label htmlFor="description">详细说明</Label>
                    <Textarea 
                      id="description" 
                      name="description"
                      placeholder="请输入详细说明..." 
                      className="min-h-[100px]"
                      value={newReward.description}
                      onChange={handleInputChange}
                    />
                  </div>
                </div>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setDialogOpen(false)}>取消</Button>
                  <Button onClick={handleSubmitReward}>提交</Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>
        </div>
        
        {/* 统计卡片 */}
        <div className="mb-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center">
                <Award className="h-5 w-5 mr-2" />
                奖惩记录概览
              </CardTitle>
              <CardDescription>
                班级学生奖惩记录统计
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="bg-yellow-50 p-4 rounded-lg">
                  <div className="flex justify-between items-center">
                    <div>
                      <p className="text-sm text-gray-500">待审批</p>
                      <p className="text-2xl font-bold text-yellow-600">{pendingCount}</p>
                    </div>
                    <div className="p-2 bg-yellow-100 rounded-full">
                      <Clock className="h-6 w-6 text-yellow-600" />
                    </div>
                  </div>
                </div>
                
                <div className="bg-green-50 p-4 rounded-lg">
                  <div className="flex justify-between items-center">
                    <div>
                      <p className="text-sm text-gray-500">已通过</p>
                      <p className="text-2xl font-bold text-green-600">{approvedCount}</p>
                    </div>
                    <div className="p-2 bg-green-100 rounded-full">
                      <ThumbsUp className="h-6 w-6 text-green-600" />
                    </div>
                  </div>
                </div>
                
                <div className="bg-red-50 p-4 rounded-lg">
                  <div className="flex justify-between items-center">
                    <div>
                      <p className="text-sm text-gray-500">已驳回</p>
                      <p className="text-2xl font-bold text-red-600">{rejectedCount}</p>
                    </div>
                    <div className="p-2 bg-red-100 rounded-full">
                      <ThumbsDown className="h-6 w-6 text-red-600" />
                    </div>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
        
        {/* 记录列表 */}
        <div className="space-y-4">
          {filteredRewards.length > 0 ? (
            filteredRewards.map((reward) => (
              <Card key={reward.id}>
                <CardHeader className="pb-2">
                  <div className="flex justify-between items-start">
                    <div>
                      <div className="flex items-center space-x-2">
                        <CardTitle className="text-lg">{reward.studentName}</CardTitle>
                        <Badge className={`${
                          reward.type === '奖励' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                        }`}>
                          {reward.type}
                        </Badge>
                        <Badge className={`${
                          reward.status === 'pending' ? 'bg-yellow-100 text-yellow-800' :
                          reward.status === 'approved' ? 'bg-green-100 text-green-800' :
                          'bg-red-100 text-red-800'
                        }`}>
                          {reward.status === 'pending' ? '待审批' :
                           reward.status === 'approved' ? '已通过' : '已驳回'}
                        </Badge>
                      </div>
                      <CardDescription>
                        学号: {reward.studentId} · 提交日期: {reward.date}
                      </CardDescription>
                    </div>
                    <div className="flex space-x-2">
                      {reward.status === 'pending' && (
                        <>
                          <Button variant="outline" size="sm" className="h-8">
                            <Edit className="h-4 w-4 mr-1" />
                            <span>编辑</span>
                          </Button>
                          <Button 
                            variant="outline" 
                            size="sm" 
                            className="h-8 text-red-600 hover:text-red-700"
                            onClick={() => handleDeleteReward(reward.id)}
                          >
                            <Trash2 className="h-4 w-4 mr-1" />
                            <span>删除</span>
                          </Button>
                        </>
                      )}
                    </div>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="space-y-2">
                    <div>
                      <span className="font-medium">原因：</span>
                      <span className="text-gray-700">{reward.reason}</span>
                    </div>
                    <div>
                      <span className="font-medium">详细说明：</span>
                      <p className="text-gray-700">{reward.description}</p>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))
          ) : (
            <div className="text-center py-8">
              <p className="text-gray-500">暂无奖惩记录</p>
            </div>
          )}
        </div>
      </div>
    </FadeIn>
  );
}
